package org.xlp.mvc.servlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xlp.json.Json;
import org.xlp.mvc.annotation.RequestMapping;
import org.xlp.mvc.enumeration.RequestMethodType;
import org.xlp.mvc.handler.ParameterNotExistException;
import org.xlp.mvc.handler.RequestMappingInfoHandler;
import org.xlp.mvc.mapping.RequestMappingInfo;
import org.xlp.mvc.mapping.RequestMappingMap;
import org.xlp.mvc.mapping.RequestPathUtils;
import org.xlp.utils.XLPCharsetUtil;
import org.xlp.utils.XLPPackingTypeUtil;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Locale;

/**
 * Create by xlp on 2022/01/01
 *
 * 对@{@link RequestMapping}路径映射拦截，并进行相应的处理
 */
public class XLPDispatchedServlet extends HttpServlet {
    private static final long serialVersionUID = -8887930386546188053L;

    private final static Logger LOGGER = LoggerFactory.getLogger(XLPDispatchedServlet.class);

    /**
     * Tomcat的默认servlet名称
     */
    public static final String COMMON_DEFAULT_SERVLET_NAME = "default";

    /**
     * 标记是否在web.xml中配置了用默认servlet处理静态资源参数名称
     */
    public static final String HAS_CONFIGURE_DEFAULT_SERVLET_PARAMETER = "configDefault";

    /**
     * 标记是否在web.xml中配置了用默认servlet处理静态资源参数,值为true时，配置了，否则没有配置
     */
    public boolean hasConfiguredDefaultServlet = false;
    
    /**
     * 路径转发前缀
     */
    public static final String DISPATCHER_PREFIX = "dispatcher:";
    
    /**
     * 路径重定向前缀
     */
    public static final String REDIRECT_PREFIX = "redirect:";

    /**
     * http协议前缀
     */
    public static final String HTTP_PROTOCOL_PREFIX = "http://";

    /**
     * https协议前缀
     */
    public static final String HTTPS_PROTOCOL_PREFIX = "https://";
    
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        String initParameter = config.getInitParameter(HAS_CONFIGURE_DEFAULT_SERVLET_PARAMETER);
        hasConfiguredDefaultServlet = "true".equals(initParameter);
    }

	protected void doService(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
			throws IOException, ServletException {
		//获取请求方式
        String requestMethod = httpServletRequest.getMethod().toUpperCase(Locale.ENGLISH);
        //把请求方式转换成枚举类型
        RequestMethodType requestMethodType = RequestMethodType.valueOf(requestMethod);
        //项目根路经
        String contextPath = httpServletRequest.getContextPath();
        //访问链接uri
        String uri = httpServletRequest.getRequestURI();
        uri = URLDecoder.decode(uri, XLPCharsetUtil.UTF8);
        //访问路径key
        String path = RequestPathUtils.removeContextPathFromUri(contextPath, uri);
        if (LOGGER.isDebugEnabled()){
            LOGGER.debug("当前访问的路径uri=" + uri);
        }
        if (path.endsWith("/")){
            path = path.substring(0, path.length() -1);
        }
        String pathKey = path +  "_" + requestMethodType.name();
        RequestMappingInfo info = RequestMappingMap.getRequestMappingInfo(pathKey);
        if(info == null){
            if (RequestMappingMap.getPathSet().contains(path)) {
                doNotSupportRequest(httpServletRequest, httpServletResponse);
                return;
            }

            RequestMappingMap.PathVariableFindInfo findInfo = RequestMappingMap.findPathVariableMapping(path, requestMethodType);
            int flag = findInfo.getFlag();
            if (flag == RequestMappingMap.PATH_EQUAL_NO_USE){
                doNotSupportRequest(httpServletRequest, httpServletResponse);
                return;
            }
            if (flag == RequestMappingMap.PATH_EQUAL) {
                info = findInfo.getRequestMappingInfo();
            }
        }

        if (info != null){
            try {
                Object value = new RequestMappingInfoHandler().handle(httpServletRequest, httpServletResponse, info);
                if (value != null){
                	 String response = doControllerMethodReturnValue(httpServletRequest, httpServletResponse, value);
                	 if (response == null) return;
                     httpServletResponse.getWriter().write(response);
                }
            } catch (IOException | ServletException e){
                throw e;
            } catch (Exception e){
                try {
                    doBadRequest(httpServletResponse, httpServletRequest, e);
                } catch (Exception ex) {
                    throw new ServletException(e);
                }
            }
        } else {
            //配置了用默认servlet处理静态资源参数, 则未找到所要访问的资源，直接返回404
            if (hasConfiguredDefaultServlet){
                httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            } else {
                //未配置了用默认servlet处理静态资源参数, 则未找到所要访问的资源，则用默认servlet处理
                httpServletRequest.getServletContext().getNamedDispatcher(COMMON_DEFAULT_SERVLET_NAME)
                        .forward(httpServletRequest, httpServletResponse);
            }
        }
	}

    /**
     * 处理异常请求
     * @param response
     * @param request
     * @param e
     */
	protected void doBadRequest(HttpServletResponse response, HttpServletRequest request,
                                Exception e) throws Exception {
	    if (e instanceof ParameterNotExistException){
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        } else {
            throw e;
        }
    }

    /**
     * 不支持的请求
     * @param request
     * @param response
     */
	protected void doNotSupportRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "不支持[" + request.getMethod().toUpperCase(Locale.ENGLISH)
                + "]请求方式！");
    }

    /**
     * 处理controller函数的返回值
     * @param httpServletRequest
     * @param httpServletResponse
     * @param value
     * @return
     */
	protected String doControllerMethodReturnValue(HttpServletRequest httpServletRequest,
                                                   HttpServletResponse httpServletResponse,
                                                   Object value) throws ServletException, IOException {
        String response;

        if (value instanceof CharSequence) {
            response = value.toString();
            //请求转发
            if (response.startsWith(DISPATCHER_PREFIX)) {
                httpServletRequest.getRequestDispatcher(response.substring(DISPATCHER_PREFIX.length()))
                        .forward(httpServletRequest, httpServletResponse);
                return null;
            }
            //请求重定向
            if (response.startsWith(REDIRECT_PREFIX)) {
                String redirectUrl = response.substring(REDIRECT_PREFIX.length());
                if (redirectUrl.startsWith(HTTP_PROTOCOL_PREFIX)
                        || redirectUrl.startsWith(HTTPS_PROTOCOL_PREFIX)){
                    httpServletResponse.sendRedirect(redirectUrl);
                    return null;
                }
                redirectUrl = RequestPathUtils.mergePath(httpServletRequest.getContextPath(), redirectUrl);
                if (!redirectUrl.startsWith("/")) {
                    redirectUrl = "/" + redirectUrl;
                }
                httpServletResponse.sendRedirect(redirectUrl);
                return null;
            }
        }

        return doControllerMethodReturnValueToJson(value, httpServletRequest, httpServletResponse);
    }

    /**
     * 处理controller函数的返回值，转换成Json格式字符串
     * @param value
     * @param httpServletRequest
     * @param httpServletResponse
     * @return
     */
    protected String doControllerMethodReturnValueToJson(Object value, HttpServletRequest httpServletRequest,
                                                         HttpServletResponse httpServletResponse){
        String response;
        Class<?> cs = value.getClass();
        // 判断返回值是否是数字类型，或基础类型，或包装类型，或字符串类型
        if (XLPPackingTypeUtil.isNumber(value)
                || XLPPackingTypeUtil.isOtherRawOrPackingType(cs)
                || value instanceof CharSequence
                || value instanceof Json){
            response = value.toString();
        } else {
            response = Json.toJsonString(value);
        }
        return response;
    }

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doService(req, resp);
	}

	@Override
	protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doService(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doService(req, resp);
	}

	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doService(req, resp);
	}

	@Override
	protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doService(req, resp);
	}

	@Override
	protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doService(req, resp);
	}

	@Override
	protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doService(req, resp);
	}
}
